package cn.bugstack.mybatis.datasource.pooled;

import java.util.ArrayList;
import java.util.List;

/**
 * description: 池状态
 * taskId：
 * <pre>
 * change history:
 * date             defect#             person                comments
 * ---------------------------------------------------------------------
 * 2024/11/29       ********         zhaochaoyue        create file
 * </pre>
 *
 * @author: zhaochaoyue
 * @date: 2024/11/29 10:20
 * @copyright: 2024
 */
public class PoolState {
    
    protected PooledDataSource dataSource;
    
    //空闲连接
    protected final List<PooledConnection> idelConnections = new ArrayList<>();
    
    //活跃连接
    protected final List<PooledConnection> activeConnections = new ArrayList<>();
    
    //请求次数
    protected long requestCount = 0;
    
    //总请求时间 累计时间
    protected long accumulatedRequestTime = 0;
    
    protected long accumulatedCheckoutTime = 0;
    //过期连接数
    protected long claimedOverdueConnectionCount=0;
    //过期累计检出时间
    protected long accumulatedCheckoutTimeOfOverdueConnections= 0;
    
    //总等待时间
    protected long accumulatedWaitTime = 0;
    
    //要等待的次数
    protected long hadToWaitCount = 0;
    
    //失败连接次数
    protected long badConnectionCount = 0;

    public PoolState(PooledDataSource dataSource) {
        this.dataSource = dataSource;
    }
    

    public synchronized long getRequestCount() {
        return requestCount;
    }

    public synchronized long getAverageAccumulatedRequestTime() {
        return requestCount== 0 ? 0 : accumulatedRequestTime/requestCount;
    }

    public synchronized long getAccumulatedCheckoutTime() {
        return claimedOverdueConnectionCount == 0 ? 0: accumulatedCheckoutTime/claimedOverdueConnectionCount;
    }

    public synchronized long getClaimedOverdueConnectionCount() {
        return claimedOverdueConnectionCount;
    }

    public synchronized long getAccumulatedCheckoutTimeOfOverdueConnections() {
        return accumulatedCheckoutTimeOfOverdueConnections;
    }

    public synchronized long getAverageAccumulatedWaitTime() {
        return hadToWaitCount == 0 ? 0: accumulatedWaitTime/hadToWaitCount;
    }

    public synchronized long getHadToWaitCount() {
        return hadToWaitCount;
    }

    public synchronized long getBadConnectionCount() {
        return badConnectionCount;
    }
    
    public synchronized long getAverageOverdueCheckoutTime(){
        return claimedOverdueConnectionCount ==0 ? 0:accumulatedCheckoutTimeOfOverdueConnections /claimedOverdueConnectionCount;
    }
    
    public synchronized int getIdleConnectionCount(){
        return idelConnections.size();
    }
    
    public synchronized int getActiveConnectionCount(){
        return activeConnections.size();
    }
    
}
